﻿#include "BaseVector.h"

#include <QDebug>

class BaseVector::BaseVectorPrivate :QObject
{
public:
	int ref_count;
	QVector<QVariant> data;
public:
	BaseVectorPrivate(QObject*parent) :QObject(parent)
	{
		ref_count = 0;
	}
	QVariant* getByIdx(int idx)
	{
		if (idx >= data.count())
			return nullptr;
		return &data.operator[](idx);
	}
};

int BaseVector::addref_fn(void*_)
{
	if (!_)
		return 0;

	IVector* ptr = (IVector*)_;

	int r = 0;
	try {
		//ptr = (BaseVector*)_;
		//BaseVector* ptr = (BaseVector*)_;
		r = ptr->addRef();
	}
	catch (...) {
		r = -10000;
	}

	qDebug() << "addref:" << r;

	return 0;
}

int BaseVector::release_fn(void*_)
{
	qDebug() << __FUNCTION__ << "," << _;
	if (!_)
		return 0;

	IVector* ptr = (IVector*)_;

	int r = 0;
	try {
		r = ptr->release();
	}
	catch (...) {
		r = -10000;
	}
	qDebug() << "release:" << r;
	if (0 == r) {
		qDebug() << "delete:" << ptr; 
		delete ptr;
	}
	return r;
}


BaseVector::BaseVector(QObject*parent) :IVector(parent), private_ptr(new BaseVectorPrivate(this))
{}

BaseVector::~BaseVector()
{}

QVector<QVariant>*BaseVector::data()
{
	return &private_ptr->data;
}
int BaseVector::type()
{
	return VECTORTYPE_NONE;
}
int BaseVector::append(QVector<QVariant>*arr)
{
	private_ptr->data.append(*arr);
	return arr->count();
}
int BaseVector::append(const QVariant&v)
{
	private_ptr->data.append(v);
	return 1;
}
int BaseVector::count()
{
	return private_ptr->data.count();
}
void BaseVector::remove(int idx)
{
	private_ptr->data.remove(idx);
}
QVariant BaseVector::get(int idx)
{
	QVariant*r = private_ptr->getByIdx(idx);
	if (r) {
		return *r;
	}
	return QVariant(QVariant::Type::Invalid);
}
int BaseVector::set(int idx, const QVariant&v)
{
	QVariant*p = private_ptr->getByIdx(idx);
	if (p) {
		*p = v;
	}
	return p ? 1 : 0;
}
int BaseVector::addRef()
{
	return ++private_ptr->ref_count;
}
int BaseVector::release()
{
	return --private_ptr->ref_count;
}

